package com.study.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.study.constant.MessageConstant;
import com.study.constant.RedisConstant;
import com.study.entity.PageResult;
import com.study.entity.QueryPageBean;
import com.study.entity.Result;
import com.study.pojo.Setmeal;
import com.study.service.SetMealService;
import com.study.utils.QiniuUtils;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.UUID;

@Controller
@ResponseBody
@RequestMapping(value = "/setmeal")
public class SetMealController {

    @Reference
    private SetMealService setMealService;
    @Resource(name = "jedisPool")
    private JedisPool jedisPool;

    @RequestMapping(value = "/upload")
    public Result upload(@RequestParam(value = "imgFile") MultipartFile imgFile){
        try{
            String originalFilename = imgFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().concat(suffix);
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //文件上传成功后，需要将文件名称保存到redis中
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            return new Result(false, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }

    }

    @RequestMapping(value = "/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        try{
            setMealService.add(setmeal,checkgroupIds);
            return new Result(false, MessageConstant.ADD_SETMEAL_SUCCESS);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    @RequestMapping(value = "/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult page = setMealService.findPage(queryPageBean);
        return page;
    }
}
